<template>
  <div class="app-container">

    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="项目标段" prop="institutionCode">
        <el-select
          v-model="queryParams.institutionCode"
          placeholder="请选择"
          size="small"
          style="width: 240px" @change="handleBidChange"
        >
          <el-option-group
            v-for="group in projectBidOptions"
            :key="group.name"
            :label="group.name">
            <el-option
              v-for="item in group.bids"
              :key="item.code"
              :label="item.name"
              :value="item.code">
            </el-option>
          </el-option-group>
        </el-select>
      </el-form-item>

    </el-form>

    <el-row :gutter="10">

      <el-col :span="8">
        <el-card style="height: calc(100vh - 200px)">
          <div slot="header">
            <span>施工队伍</span>
            <el-button
              style="float: right; padding: 3px 0"
              type="text"
              icon="el-icon-refresh-right"
              @click="refreshBattalion"
            ></el-button>
          </div>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="handleAddBattalion"
                v-hasPermi="['labour:battalion:add']"
              >新增</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="info"
                plain
                icon="el-icon-upload2"
                size="mini"
                @click="handleImport(1)"
                v-hasPermi="['labour:battalion:add']"
              >导入</el-button>
            </el-col>
          </el-row>
          <el-table
            v-loading="loading"
            :data="battalionList"
            :height="tableHeight"
            highlight-current-row
            style="width: 100%"
          >
            <el-table-column
              label="序号"
              width="60"
              align="center"
              prop="orderNum"
            ></el-table-column>

            <el-table-column
              label="队伍名称"
              align="center"
              prop="battalionName"
              :show-overflow-tooltip="true"
            ></el-table-column>

            <el-table-column
              label="操作"
              width="60"
              align="center"
              class-name="small-padding fixed-width"
            >
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdateBattalion(scope.row)"
                  v-hasPermi="['labour:battalion:edit']"
                ></el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDeleteBattalion(scope.row)"
                  v-hasPermi="['labour:battalion:remove']"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="battalionTotal>0"
            :total="battalionTotal"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getBattalionList"
          />
        </el-card>
      </el-col>

      <el-col :span="8">
        <el-card style="height: calc(100vh - 200px)">
          <div slot="header">
            <span>施工班组</span>
            <el-button
              style="float: right; padding: 3px 0"
              type="text"
              icon="el-icon-refresh-right"
              @click="refreshTeam"
            ></el-button>
          </div>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="handleAddTeam"
                v-hasPermi="['labour:battalion:add']"
              >新增</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="info"
                plain
                icon="el-icon-upload2"
                size="mini"
                @click="handleImport(2)"
                v-hasPermi="['labour:battalion:add']"
              >导入</el-button>
            </el-col>
          </el-row>
          <el-table
            v-loading="teamLoading"
            :data="teamList"
            :height="tableHeight"
            highlight-current-row
            style="width: 100%"
          >
            <el-table-column
              label="序号"
              width="60"
              align="center"
              prop="orderNum"
            ></el-table-column>

            <el-table-column
              label="班组名称"
              align="center"
              prop="teamName"
              :show-overflow-tooltip="true"
            ></el-table-column>

            <el-table-column
              label="操作"
              width="60"
              align="center"
              class-name="small-padding fixed-width"
            >
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdateTeam(scope.row)"
                  v-hasPermi="['labour:battalion:edit']"
                ></el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDeleteTeam(scope.row)"
                  v-hasPermi="['labour:battalion:remove']"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="teamTotal>0"
            :total="teamTotal"
            :page.sync="teamQueryParams.pageNum"
            :limit.sync="teamQueryParams.pageSize"
            @pagination="getTeamList"
          />
        </el-card>
      </el-col>

      <el-col :span="8">
        <el-card style="height: calc(100vh - 200px)">
          <div slot="header">
            <span>岗位工种</span>
            <el-button
              style="float: right; padding: 3px 0"
              type="text"
              icon="el-icon-refresh-right"
              @click="refreshPost"
            ></el-button>
          </div>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="handleAddPost"
                v-hasPermi="['labour:battalion:add']"
              >新增</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="info"
                plain
                icon="el-icon-upload2"
                size="mini"
                @click="handleImport(3)"
                v-hasPermi="['labour:battalion:add']"
              >导入</el-button>
            </el-col>
          </el-row>
          <el-table
            v-loading="postLoading"
            :data="postList"
            :height="tableHeight"
            highlight-current-row
            style="width: 100%"
          >
            <el-table-column
              label="序号"
              width="60"
              align="center"
              prop="orderNum"
            ></el-table-column>

            <el-table-column
              label="工种名称"
              align="center"
              prop="postName"
              :show-overflow-tooltip="true"
            ></el-table-column>

            <el-table-column
              label="操作"
              width="60"
              align="center"
              class-name="small-padding fixed-width"
            >
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdatePost(scope.row)"
                  v-hasPermi="['labour:battalion:edit']"
                ></el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDeletePost(scope.row)"
                  v-hasPermi="['labour:battalion:remove']"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="postTotal>0"
            :total="postTotal"
            :page.sync="postQueryParams.pageNum"
            :limit.sync="postQueryParams.pageSize"
            @pagination="getPostList"
          />
        </el-card>
      </el-col>

    </el-row>

    <!-- 添加或修改施工队伍对话框 -->
    <el-dialog :title="battalionTitle" :visible.sync="battalionOpen" :close-on-click-modal="false" style="margin-top: 150px" width="500px" append-to-body>
      <el-form ref="battalionForm" :model="battalionForm" :rules="battalionRules" label-width="80px">
        <el-form-item label="队伍名称" prop="battalionName">
          <el-input v-model="battalionForm.battalionName" placeholder="请输入队伍名称" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitBattalionForm">确 定</el-button>
        <el-button @click="cancelBattalion">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改施工班组对话框 -->
    <el-dialog :title="teamTitle" :visible.sync="teamOpen" :close-on-click-modal="false" style="margin-top: 150px" width="500px" append-to-body>
      <el-form ref="teamForm" :model="teamForm" :rules="teamRules" label-width="80px">
        <el-form-item label="队伍名称" prop="teamName">
          <el-input v-model="teamForm.teamName" placeholder="请输入班组名称" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitTeamForm">确 定</el-button>
        <el-button @click="cancelTeam">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改岗位工种对话框 -->
    <el-dialog :title="postTitle" :visible.sync="postOpen" :close-on-click-modal="false" style="margin-top: 150px" width="500px" append-to-body>
      <el-form ref="postForm" :model="postForm" :rules="postRules" label-width="80px">
        <el-form-item label="工种名称" prop="postName">
          <el-input v-model="postForm.postName" placeholder="请输入工种名称" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitPostForm">确 定</el-button>
        <el-button @click="cancelPost">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 数据导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" :close-on-click-modal="false" style="margin-top: 150px" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport+ '&institutionCode=' + this.queryParams.institutionCode"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 覆盖更新
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="downloadTemplate">下载模板</el-link>
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入结果对话框 -->
    <el-dialog :title="result.title" :visible.sync="result.open" width="600px" append-to-body>
      <el-table :data="result.rows" :height="tableHeight" highlight-current-row>
        <el-table-column label="行号" align="center" prop="row" />
        <el-table-column label="内容" align="center" prop="content" width="400" show-overflow-tooltip />
        <el-table-column label="状态" align="center">
          <template slot-scope="scope">
            <el-button size="mini" v-if="scope.row.status=='success'" type="success" icon="el-icon-check" circle></el-button>
            <el-button size="mini" v-if="scope.row.status=='error'" type="danger" icon="el-icon-close" circle></el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="result.open = false">关 闭</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import { selectProjectBidBranch } from "@/api/project/bid";
  import { listBattalion, addBattalion, getBattalion, updateBattalion, delBattalion, downloadTemplate } from "@/api/site/labour/battalion";
  import { listTeam, addTeam, getTeam, updateTeam, delTeam, downloadTeamTemplate } from "@/api/site/labour/team";
  import { listPost, addPost, getPost, updatePost, delPost, downloadPostTemplate } from "@/api/site/labour/post";
  import { getToken } from "@/utils/auth";

  export default {
    name: "Battalion",
    data() {
      return {
        // 遮罩层
        loading: false,
        teamLoading: false,
        postLoading: false,
        // 项目标段分组下拉框
        projectBidOptions: [],
        // 显示搜索条件
        showSearch: true,
        // 选中数组
        battalionIds: [],
        // 总条数
        battalionTotal: 0,
        teamTotal: 0,
        postTotal: 0,
        // 施工队伍表格数据
        battalionList: [],
        // 施工班组表格数据
        teamList: [],
        // 岗位工种表格数据
        postList: [],
        tableHeight: window.innerHeight - 400,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          institutionCode: undefined
        },
        battalionTitle: "",
        battalionOpen: false,
        teamTitle: "",
        teamOpen: false,
        postTitle: "",
        postOpen: false,
        // 表单参数
        battalionForm: {},
        teamForm: {},
        postForm: {},
        battalionRules: {
          battalionName: [
            { required: true, message: "队伍名称不能为空", trigger: "blur" },
            { max: 120, message: '队伍名称最大长度为120个字符', trigger: 'blur'}
          ]
        },
        teamRules: {
          teamName: [
            { required: true, message: "班组名称不能为空", trigger: "blur" },
            { max: 120, message: '班组名称最大长度为120个字符', trigger: 'blur'}
          ]
        },
        postRules: {
          postName: [
            { required: true, message: "工种名称不能为空", trigger: "blur" },
            { max: 120, message: '工种名称最大长度为120个字符', trigger: 'blur'}
          ]
        },
        teamQueryParams: {
          pageNum: 1,
          pageSize: 10,
          institutionCode: undefined
        },
        postQueryParams: {
          pageNum: 1,
          pageSize: 10,
          institutionCode: undefined
        },
        // 导入参数
        upload: {
          type: 1,
          // 是否显示弹出层（导入）
          open: false,
          // 弹出层标题（导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 覆盖更新
          updateSupport: 0,
          // 设置上传的请求头部
          headers: { token: "Bearer " + getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/labour/battalion/importData",
          excelRows: [],
        },
        // 导入结果参数
        result: {
          open: false,
          title: "",
          rows: [],
        },
        // 帮助参数
        help: {
          // 是否显示弹出层（帮助）
          open: false,
          // 弹出层标题（帮助）
          title: ""
        }
      }
    },
    created() {
      this.initBidSelect();
    },
    methods: {
      /** 初始化标段下拉框 */
      initBidSelect() {
        selectProjectBidBranch().then(response => {
          this.projectBidOptions = response.data;
          if (this.projectBidOptions.length > 0) {
            this.queryParams.institutionCode = this.projectBidOptions[0].bids[0].code;
            this.teamQueryParams.institutionCode = this.projectBidOptions[0].bids[0].code;
            this.postQueryParams.institutionCode = this.projectBidOptions[0].bids[0].code;
            this.getBattalionList();
            this.getTeamList();
            this.getPostList();
          }
        });
      },
      // 标段下拉框发生变化
      handleBidChange() {
        this.queryParams.pageNum = 1;
        this.getBattalionList();
        this.teamQueryParams.pageNum = 1;
        this.teamQueryParams.institutionCode = this.queryParams.institutionCode;
        this.getTeamList();
        this.postQueryParams.pageNum = 1;
        this.postQueryParams.institutionCode = this.queryParams.institutionCode;
        this.getPostList();
      },
      /** 查询施工队伍列表 */
      getBattalionList() {
        this.loading = true;
        listBattalion(this.queryParams).then(response => {
          this.battalionList = response.rows;
          this.battalionTotal = response.total;
          this.loading = false;
        });
      },
      // 查询施工班组列表
      getTeamList() {
        this.teamLoading = true;
        listTeam(this.teamQueryParams).then(response => {
          this.teamList = response.rows;
          this.teamTotal = response.total;
          this.teamLoading = false;
        });
      },
      // 查询岗位工种列表
      getPostList() {
        this.postLoading = true;
        listPost(this.postQueryParams).then(response => {
          this.postList = response.rows;
          this.postTotal = response.total;
          this.postLoading = false;
        });
      },
      // 刷新施工队伍列表
      refreshBattalion() {
        this.getBattalionList();
      },
      // 刷新施工班组列表
      refreshTeam() {
        this.getTeamList();
      },
      // 刷新岗位工种列表
      refreshPost() {
        this.getPostList();
      },
      // 取消按钮
      cancelBattalion() {
        this.battalionOpen = false;
        this.resetBattalion();
      },
      cancelTeam() {
        this.teamOpen = false;
        this.resetTeam();
      },
      cancelPost() {
        this.postOpen = false;
        this.resetPost();
      },
      // 表单重置
      resetBattalion() {
        this.battalionForm = {
          battalionId: null,
          battalionName: null,
          institutionCode: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null
        };
        this.resetForm("battalionForm");
      },
      resetTeam() {
        this.teamForm = {
          teamId: null,
          teamName: null,
          institutionCode: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null
        };
        this.resetForm("teamForm");
      },
      resetPost() {
        this.postForm = {
          postId: null,
          postName: null,
          institutionCode: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null
        };
        this.resetForm("postForm");
      },
      /** 新增按钮操作 */
      handleAddBattalion() {
        if (this.queryParams.institutionCode == null) {
          this.$modal.msgError("请先选择项目标段");
          return;
        }
        this.resetBattalion();
        this.battalionOpen = true;
        this.battalionTitle = "添加施工队伍";
      },
      handleAddTeam() {
        if (this.teamQueryParams.institutionCode == null) {
          this.$modal.msgError("请先选择项目标段");
          return;
        }
        this.resetTeam();
        this.teamOpen = true;
        this.teamTitle = "添加施工班组";
      },
      handleAddPost() {
        if (this.postQueryParams.institutionCode == null) {
          this.$modal.msgError("请先选择项目标段");
          return;
        }
        this.resetPost();
        this.postOpen = true;
        this.postTitle = "添加岗位工种";
      },
      /** 修改按钮操作 */
      handleUpdateBattalion(row) {
        this.resetBattalion();
        const battalionId = row.battalionId;
        getBattalion(battalionId).then(response => {
          this.battalionForm = response.data;
          this.battalionOpen = true;
          this.battalionTitle = "修改施工队伍";
        });
      },
      handleUpdateTeam(row) {
        this.resetTeam();
        const teamId = row.teamId;
        getTeam(teamId).then(response => {
          this.teamForm = response.data;
          this.teamOpen = true;
          this.teamTitle = "修改施工班组";
        });
      },
      handleUpdatePost(row) {
        this.resetPost();
        const postId = row.postId;
        getPost(postId).then(response => {
          this.postForm = response.data;
          this.postOpen = true;
          this.postTitle = "修改岗位工种";
        });
      },
      /** 提交按钮 */
      submitBattalionForm() {
        this.$refs["battalionForm"].validate(valid => {
          if (valid) {
            if (this.battalionForm.battalionId != null) {
              updateBattalion(this.battalionForm).then(response => {
                this.$modal.msgSuccess("操作成功");
                this.battalionOpen = false;
                this.getBattalionList();
              });
            } else {
              this.battalionForm.institutionCode = this.queryParams.institutionCode;
              addBattalion(this.battalionForm).then(response => {
                this.$modal.msgSuccess("操作成功");
                this.battalionOpen = false;
                this.getBattalionList();
              });
            }
          }
        });
      },
      submitTeamForm() {
        this.$refs["teamForm"].validate(valid => {
          if (valid) {
            if (this.teamForm.teamId != null) {
              updateTeam(this.teamForm).then(response => {
                this.$modal.msgSuccess("操作成功");
                this.teamOpen = false;
                this.getTeamList();
              });
            } else {
              this.teamForm.institutionCode = this.teamQueryParams.institutionCode;
              addTeam(this.teamForm).then(response => {
                this.$modal.msgSuccess("操作成功");
                this.teamOpen = false;
                this.getTeamList();
              });
            }
          }
        });
      },
      submitPostForm() {
        this.$refs["postForm"].validate(valid => {
          if (valid) {
            if (this.postForm.postId != null) {
              updatePost(this.postForm).then(response => {
                this.$modal.msgSuccess("操作成功");
                this.postOpen = false;
                this.getPostList();
              });
            } else {
              this.postForm.institutionCode = this.postQueryParams.institutionCode;
              addPost(this.postForm).then(response => {
                this.$modal.msgSuccess("操作成功");
                this.postOpen = false;
                this.getPostList();
              });
            }
          }
        });
      },
      // 删除施工班组
      handleDeleteTeam(row) {
        const teamId = row.teamId;
        this.$modal.confirm('确认删除选中的数据项？').then(function() {
          return delTeam(teamId);
        }).then(() => {
          this.getTeamList();
          this.$modal.msgSuccess("操作成功");
        }).catch(() => {});
      },
      // 删除施工队伍
      handleDeleteBattalion(row) {
        const battalionId = row.battalionId;
        this.$modal.confirm('确认删除选中的数据项？').then(function() {
          return delBattalion(battalionId);
        }).then(() => {
          this.getBattalionList();
          this.$modal.msgSuccess("操作成功");
        }).catch(() => {});
      },
      // 删除岗位工种
      handleDeletePost(row) {
        const postId = row.postId;
        this.$modal.confirm('确认删除选中的数据项？').then(function() {
          return delPost(postId);
        }).then(() => {
          this.getPostList();
          this.$modal.msgSuccess("操作成功");
        }).catch(() => {});
      },
      // 数据导入
      handleImport(type) {
        this.result.rows = [];
        this.upload.type = type;
        if (type == 1) {
          this.upload.title = "施工队伍导入";
          this.upload.url = process.env.VUE_APP_BASE_API + "/labour/battalion/importData";
        } else if (type == 2) {
          this.upload.title = "施工班组导入";
          this.upload.url = process.env.VUE_APP_BASE_API + "/labour/team/importData";
        } else if (type == 3) {
          this.upload.title = "岗位工种导入";
          this.upload.url = process.env.VUE_APP_BASE_API + "/labour/post/importData";
        }
        this.upload.open = true;
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.result.rows = response.rows;
        if (response.status == "success") {
          if (this.upload.type == 1) {
            this.getBattalionList();
          } else if (this.upload.type == 2) {
            this.getTeamList();
          } else if (this.upload.type == 3) {
            this.getPostList();
          }
        }
        this.$confirm(response.msg, '导入结果', {
          showCancelButton: true,
          showConfirmButton: response.rows != undefined,
          confirmButtonText: '详情',
          cancelButtonText: '取消',
          type: response.status
        }).then(() => {
          this.result.title = "查看导入详情";
          this.result.open = true;
        }).catch(() => {
        });
      },
      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit();
      },
      /** 下载模板操作 */
      downloadTemplate() {
        if (this.upload.type == 1) {
          downloadTemplate().then(response => {
            this.$download.name(response.msg);
          });
        } else if (this.upload.type == 2) {
          downloadTeamTemplate().then(response => {
            this.$download.name(response.msg);
          });
        } else if (this.upload.type == 3) {
          downloadPostTemplate().then(response => {
            this.$download.name(response.msg);
          });
        }

      },

    }
  }
</script>
